package com.mcxx.modules.tool.service.impl;

import com.mcxx.common.ExternalFileUtil;
import com.mcxx.modules.external.jinmin.entity.JMBAF01Entity;
import com.mcxx.modules.external.jinmin.entity.JMBAF97Entity;
import com.mcxx.modules.external.jinmin.entity.JMBAP01Entity;
import com.mcxx.modules.external.jinmin.entity.JMBAP97Entity;
import com.mcxx.modules.external.jinmin.service.read.JMBAF01ReadService;
import com.mcxx.modules.external.jinmin.service.write.JMBAF01WriteService;
import com.mcxx.modules.external.jinmin.service.write.JMBAF97WriteService;
import com.mcxx.modules.external.jinmin.service.write.JMBAP01WriteService;
import com.mcxx.modules.external.jinmin.service.write.JMBAP97WriteService;
import com.mcxx.modules.miniSalvation.family.dto.FamilyMemberDTO;
import com.mcxx.modules.miniSalvation.family.entity.FamilyMainHistoryEntity;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMainHistoryReadService;
import com.mcxx.modules.miniSalvation.family.service.read.FamilyMemberHistoryReadService;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderReadService;
import com.mcxx.modules.miniSalvation.salary.entity.FamilySalaryEntity;
import com.mcxx.modules.miniSalvation.salary.entity.MemberSalaryEntity;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilySalaryReadService;
import com.mcxx.util.Constant;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@TaTransactional
public class JinminExitService {

    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(JinminExitService.class);

    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private FamilyMainHistoryReadService familyMainHistoryReadService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private FamilySalaryReadService familySalaryReadService;
    @Autowired
    private FamilyMemberSalaryReadService familyMemberSalaryReadService;
    @Autowired
    private JMBAF01ReadService jmBAF01ReadService;
    @Autowired
    private JMBAF01WriteService jmBAF01WriteService;
    @Autowired
    private JMBAF97WriteService jmBAF97WriteService;
    @Autowired
    private JMBAP01WriteService jmBAP01WriteService;
    @Autowired
    private JMBAP97WriteService jmBAP97WriteService;

    private static String donePath = "/home/society/application/jinmin/jm_db_done.txt";
    private static String errPath = "/home/society/application/jinmin/jm_error.txt";


    public void dibaotekunData(String strMonths, String orderId, String batchNo){
        try{

            OrderEntity order = new OrderEntity();
            FamilyMainHistoryEntity family = new FamilyMainHistoryEntity();
            List<FamilyMemberDTO> memberList = new ArrayList<>();
            FamilySalaryEntity familySumSalary = new FamilySalaryEntity();
            List<MemberSalaryEntity> memberSalary = new ArrayList<>();

            order = orderReadService.getById(orderId);
            if(null == order){
                ExternalFileUtil.writeLog(errPath,"未查询到业务记录,orderId:"+orderId);
                return;
            }

            family = familyMainHistoryReadService.getByOrderId(orderId);
            if(null == family){
                ExternalFileUtil.writeLog(errPath,"未查询到家庭历史记录,orderId:"+orderId);
                return;
            }

            memberList = familyMemberHistoryReadService.listByOrderId(orderId);
            if(CollectionUtils.isEmpty(memberList)){
                ExternalFileUtil.writeLog(errPath,"未查询到成员历史记录,orderId:"+orderId);
                return;
            }

            familySumSalary = familySalaryReadService.getFamilySumSalaryByOrderId(orderId);
            if(null == familySumSalary){
                ExternalFileUtil.writeLog(errPath,"未查询到家庭待遇记录,orderId:"+orderId);
                return;
            }

            memberSalary = familyMemberSalaryReadService.queryMemberSalaryByOrderId(orderId);
            if(CollectionUtils.isEmpty(memberSalary)){
                ExternalFileUtil.writeLog(errPath,"未查询到成员待遇记录,orderId:"+orderId);
                return;
            }
            this.save(strMonths,batchNo,order,family,memberList,familySumSalary,memberSalary);

        }catch (Exception e){
            ExternalFileUtil.writeLog(errPath,e.getMessage()+"orderID:"+orderId);
            e.printStackTrace();
        }
    }

    private void save(String month,String batchNo,OrderEntity order,FamilyMainHistoryEntity family,
                      List<FamilyMemberDTO> memberList,FamilySalaryEntity familySumSalary,
                      List<MemberSalaryEntity> memberSalary){

        Map<String,Boolean> booleanMap = new HashMap<>();
        booleanMap.put("isAddMemberExt",false);
        booleanMap.put("changeFamily",false);
        booleanMap.put("familExists",false);
        String newFamilyId = Constant.getUUID();
        Map<String,String> newMemberIdMap = new HashMap<>();
        Date fristInDate = jmBAF01ReadService.getFristInDate(order.getOrderId(), order.getSourOrderId(), familySumSalary.getStartDate());

        JMBAF01Entity baf01 = this.createFamily(month, batchNo,order,family,
                booleanMap,newFamilyId);
        JMBAF97Entity baf97 = this.createFamilySalary(month, batchNo,order,family,familySumSalary,fristInDate,
                booleanMap,newFamilyId);
        List<JMBAP01Entity> bap01s = this.createMembers(month, batchNo,memberList,memberSalary,
                booleanMap,newFamilyId,newMemberIdMap);
        List<JMBAP97Entity> bap97s = this.createMemberSalary(month, batchNo, order, family,memberList,memberSalary,fristInDate,
                booleanMap,newFamilyId,newMemberIdMap);

        Boolean isAddMemberExt = booleanMap.get("isAddMemberExt");
        Boolean changeFamily = booleanMap.get("changeFamily");
        Boolean familExists = booleanMap.get("familExists");

        if (CollectionUtils.isEmpty(bap01s)) {
            ExternalFileUtil.writeLog(errPath,"家庭成员为空,orderId:"+order.getOrderId());
            return;
        }
        if (CollectionUtils.isEmpty(bap97s)) {
            ExternalFileUtil.writeLog(errPath,"成员待遇为空,orderId:"+order.getOrderId());
            return;
        }
        try{
            if(familExists && !changeFamily){
                System.out.println("----------");
            }else{
                int i = jmBAF01WriteService.insertIgnoreNull(baf01);
                if(i <= 0){
                    ExternalFileUtil.writeLog(errPath,"保存家庭基础信息失败,orderId:"+order.getOrderId());
                    throw new RuntimeException();
                }
                int i1 = jmBAF97WriteService.insertIgnoreNull(baf97);
                if(i1 <= 0){
                    ExternalFileUtil.writeLog(errPath,"保存家庭待遇信息失败,orderId:"+order.getOrderId());
                    throw new RuntimeException();
                }
            }

            int inserts = jmBAP01WriteService.inserts(bap01s);
            if(inserts <= 0){
                ExternalFileUtil.writeLog(errPath,"保存成员基础信息失败,orderId:"+order.getOrderId());
                throw new RuntimeException();
            }
            int inserts1 = jmBAP97WriteService.inserts(bap97s);
            if(inserts1 <= 0){
                ExternalFileUtil.writeLog(errPath,"保存成员待遇信息失败,orderId:"+order.getOrderId());
                throw new RuntimeException();
            }

            ExternalFileUtil.writeLog(donePath,order.getOrderId());
        }catch (Exception e){
            ExternalFileUtil.writeLog(errPath,e.getMessage()+"orderID:"+order.getOrderId());
            e.printStackTrace();
        }

    }
    private JMBAF01Entity createFamily(String month,String batchNo,OrderEntity order,FamilyMainHistoryEntity family,
                                       Map<String,Boolean> booleanMap,
                                       String newFamilyId){
        JMBAF01Entity main = new JMBAF01Entity();

        JMBAF01Entity param = new JMBAF01Entity();
        param.setABAF0101(family.getFamilyId());
        JMBAF01Entity familyMainByParam = jmBAF01ReadService.getFamilyMainByParam(param);
        if(null == familyMainByParam){
            param = new JMBAF01Entity();
            param.setAXDF0004(family.getIdcard());
            familyMainByParam = jmBAF01ReadService.getFamilyMainByParam(param);
        }
        Boolean changeFamily = booleanMap.get("changeFamily");
        Boolean familExists = booleanMap.get("familExists");

        if(null != familyMainByParam){
            familExists = true;
            booleanMap.put("familExists",familExists);
            if(!familyMainByParam.getABAX6002().equals(JinminUtils.getSalvType(order.getBusinessType()))){

                changeFamily = true;
                booleanMap.put("changeFamily",changeFamily);
            }else{
                return null;
            }
        }
        if(changeFamily){
            main.setABAF0101(newFamilyId);
        }else{
            main.setABAF0101(family.getFamilyId());
        }
        //main.setABAF0101(family.getFamilyId());
        main.setAXDF0002(family.getName());
        main.setAXDF0004(family.getIdcard());
        main.setAXDF0011(JinminUtils.cutPhone(family.getPhone(),18));
        main.setAXDF0008(StringUtils.isNotBlank(family.getAddress()) ? family.getAddress() : order.getAreaCode());
        main.setAXDF0224("");
        main.setAXAA2701(order.getAreaCode());
        main.setABAX6002(JinminUtils.getSalvType(order.getBusinessType()));
        main.setAXDF0005(family.getFamilyNumber().toString());
        main.setABAF0012(family.getSaveMemberNumber()+"");
        main.setABAF0006(family.getFamilyRevenue());
        main.setABAF0043(JinminUtils.getCityOrVill(order.getStandType()));
        main.setABAF0027("02".equals(family.getFamilyObjectType()) ? "02" : "99");
        main.setDATA_ISSUE(month);
        main.setUPDATETIME(new Date());
        main.setDATA_STATE("I");
        main.setUP_NUM(batchNo);
        return main;
    }
    private JMBAF97Entity createFamilySalary(String month,String batchNo,OrderEntity order,
                                             FamilyMainHistoryEntity family,FamilySalaryEntity familySumSalary,Date fristInDate,
                                             Map<String,Boolean> booleanMap,
                                             String newFamilyId){
        JMBAF97Entity main = new JMBAF97Entity();
        main.setABAF9701(Constant.getUUID());
        Boolean changeFamily = booleanMap.get("changeFamily");
        if(changeFamily){
            main.setABAF0101(newFamilyId);
        }else{
            main.setABAF0101(family.getFamilyId());
        }
        //main.setABAF0101(family.getFamilyId());
        main.setAXDF0004(order.getIdcard());
        main.setABAX6002(JinminUtils.getSalvType(order.getBusinessType()));
        main.setABAP0050(StringUtils.isNotBlank(order.getReason()) ? order.getReason() : "其他");
        main.setABAP0040(familySumSalary.getSalaryNumber());
        main.setABAP0047(0.0);
        main.setABAP0048(0.0);
        main.setABAP0042(fristInDate);
        main.setABAP0043(JinminUtils.getEndMonth(familySumSalary.getEndDate(),month));
        main.setABAF0025("01");

        if (Constant.BusinessCode.TEKUN.equals(order.getBusinessType())) {
            if (StringUtils.isEmpty(family.getSupplyOrgId())) {
                main.setABAF0008("02");
            } else {
                main.setABAF0008(family.getSupplyType());
                main.setABAF0009(order.getSupplyOrgName());
            }
            main.setABAP0045(familySumSalary.getBaseSalvNumber());
            main.setABAP0044(familySumSalary.getNursingNumber());
        }
        main.setABAP0046("");
        main.setABAP0049(family.getRemark());
        main.setDATA_ISSUE(month);
        main.setUPDATETIME(new Date());
        main.setDATA_STATE("I");
        main.setUP_NUM(batchNo);
        return main;
    }
    private List<JMBAP01Entity> createMembers(String month,String batchNo,List<FamilyMemberDTO> memberList,List<MemberSalaryEntity> memberSalary,
                                              Map<String,Boolean> booleanMap,
                                              String newFamilyId,Map<String,String> newMemberIdMap){
        List<JMBAP01Entity> list = new ArrayList<>();
        Boolean changeFamily = booleanMap.get("changeFamily");
        Boolean isAddMemberExt = booleanMap.get("isAddMemberExt");
        for(FamilyMemberDTO m : memberList){
            if (!"1".equals(m.getIsSaveObject())) {
                continue;
            }
            if (!"01".equals(m.getState())) {
                continue;
            }
            Boolean find = false;
            for (MemberSalaryEntity ms : memberSalary) {
                if (ms.getMemberId().equals(m.getMemberId())) {
                    find = true;
                    break;
                }
            }
            if (!find) {
                continue;
            }

            String newMemberId = m.getMemberId();
            if(changeFamily){
                newMemberId = Constant.getUUID();
                newMemberIdMap.put(m.getIdcard(),newMemberId);
            }else{
                JMBAP01Entity param = new JMBAP01Entity();
                param.setABAF0101(m.getFamilyId());
                param.setABAP0101(m.getMemberId());
                JMBAP01Entity member = jmBAF01ReadService.getMemberMainByParam(param);
                if(null != member){
                    continue;
                }else{
                    param = new JMBAP01Entity();
                    param.setABAP0101(m.getMemberId());
                    JMBAP01Entity member1 = jmBAF01ReadService.getMemberMainByParam(param);
                    if(null != member1){
                        newMemberId = Constant.getUUID();
                        newMemberIdMap.put(m.getIdcard(),newMemberId);
                        isAddMemberExt = true;
                        booleanMap.put("isAddMemberExt",isAddMemberExt);
                    }
                }
            }
            JMBAP01Entity main = new JMBAP01Entity();
            main.setABAP0101(newMemberId);
            main.setABAF0101(changeFamily == true ? newFamilyId : m.getFamilyId());
            main.setAXCP0005(m.getIdcard());
            main.setAXCP0002(m.getName());
            main.setAXCP0006(("1".equals(m.getSex()) || "2".equals(m.getSex())) ? m.getSex() : "0");
            main.setAXCP0097(m.getBirthday());
            main.setAXCP0008(JinminUtils.getNational(m.getNation()));
            main.setAXCP0024(JinminUtils.getWorkPower(m.getWorkPower()));
            main.setABAP0022(StringUtils.isEmpty(m.getDisabilityType()) ? "0" : "1");
            main.setABAP0007(m.getDisabilityType());
            main.setABAP0008(JinminUtils.getDisableLevel(m.getDisabilityLevel()));
            main.setABAP0009(m.getDisabilityNo());
            main.setAXCP0010(StringUtils.isNotEmpty(m.getHealthState()) ? m.getHealthState() : "20");
            main.setAXCP0009(JinminUtils.getEducation(m.getEducation()));
            main.setABAP0003("99");
            main.setABAP0002(StringUtils.isNotEmpty(m.getWorkState()) ? m.getWorkState() : "03");
            main.setAXCP0092(StringUtils.isNotEmpty(m.getMarryState()) ? m.getMarryState() : "90");
            main.setABAP0005(JinminUtils.getSickType(m.getSeriousDisease()));
            main.setABAP0023((StringUtils.isNotEmpty(m.getIdcard()) && m.getIdcard().startsWith("43")) ? "1" : "0");
            main.setABAP0010(m.getSelfcareLevel());
            main.setAXCP0012("1");
            main.setABAF0004(m.getCensusPlace());
            main.setAXCP0013(m.getCensusType());
            main.setAXCP0035(m.getFamilyRelation());
            main.setABAP0017("1");
            main.setAXCP0003("");
            main.setABAP0029(0.0);
            main.setDATA_ISSUE(month);
            main.setUPDATETIME(new Date());
            main.setDATA_STATE("I");
            main.setUP_NUM(batchNo);
            list.add(main);
        }
        return list;
    }
    private List<JMBAP97Entity> createMemberSalary(String month,String batchNo,OrderEntity order,FamilyMainHistoryEntity family,
                                                   List<FamilyMemberDTO> memberList,List<MemberSalaryEntity> memberSalary,Date fristInDate,
                                                   Map<String,Boolean> booleanMap,
                                                   String newFamilyId,Map<String,String> newMemberIdMap){
        List<JMBAP97Entity> list = new ArrayList<>();
        Boolean changeFamily = booleanMap.get("changeFamily");
        Boolean isAddMemberExt = booleanMap.get("isAddMemberExt");
        for(FamilyMemberDTO m : memberList){
            if (!"1".equals(m.getIsSaveObject())) {
                continue;
            }
            if (!"01".equals(m.getState())) {
                continue;
            }
            Boolean find = false;
            MemberSalaryEntity salaryEntity = new MemberSalaryEntity();
            for (MemberSalaryEntity ms : memberSalary) {
                if (ms.getMemberId().equals(m.getMemberId())) {
                    salaryEntity = ms;
                    find = true;
                    break;
                }
            }
            if (!find) {
                continue;
            }
            if(isAddMemberExt){
                if(!newMemberIdMap.containsKey(m.getIdcard())){
                    continue;
                }
            }else{
                if(!changeFamily){
                    JMBAP01Entity param = new JMBAP01Entity();
                    param.setABAF0101(m.getFamilyId());
                    param.setABAP0101(m.getMemberId());
                    JMBAP01Entity member = jmBAF01ReadService.getMemberMainByParam(param);
                    if(null != member){
                        continue;
                    }
                }
            }

            JMBAP97Entity main = new JMBAP97Entity();
            main.setABAP9701(Constant.getUUID());
            main.setABAF0101(changeFamily == true ? newFamilyId : m.getFamilyId());
            main.setABAP0101(newMemberIdMap.containsKey(m.getIdcard()) ? newMemberIdMap.get(m.getIdcard()) : m.getMemberId());
            main.setAXCP0005(m.getIdcard());
            main.setABAX6002(JinminUtils.getSalvType(order.getBusinessType()));
            main.setABAP0040(salaryEntity.getSalaryNumber());
            main.setABAP0047(0.0);
            main.setABAP0048(0.0);
            main.setABAP0042(fristInDate);
            main.setABAP0043(JinminUtils.getEndMonth(salaryEntity.getEndDate(),month));
            main.setABAF0008("130".equals(order.getBusinessType()) ? family.getSupplyType() : null);
            main.setABAF0009("130".equals(order.getBusinessType()) ? order.getSupplyOrgName() : null);
            main.setABAP0049("");
            main.setDATA_ISSUE(month);
            main.setUPDATETIME(new Date());
            main.setDATA_STATE("I");
            main.setUP_NUM(batchNo);
            list.add(main);
        }
        return list;
    }
}
